package cn.edu.zut.score.service.impl;

import cn.edu.zut.score.core.cache.RedisCache;
import cn.edu.zut.score.core.convert.ConfigConvert;
import cn.edu.zut.score.core.domain.PageResponse;
import cn.edu.zut.score.core.domain.RestResponse;
import cn.edu.zut.score.core.dto.request.ConfigPageRequest;
import cn.edu.zut.score.core.dto.response.ConfigResponse;
import cn.edu.zut.score.core.entity.Config;
import cn.edu.zut.score.mapper.ConfigMapper;
import cn.edu.zut.score.service.IConfigService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zby
 * @since 2021-06-26
 */
@Service
public class ConfigServiceImpl extends ServiceImpl<ConfigMapper, Config> implements IConfigService {

    @Autowired(required = false)
    private HttpServletRequest httpServletRequest;

    @Autowired
    private RedisCache redisCache;

    @Autowired(required = false)
    private ConfigMapper configMapper;

    @Override
    public RestResponse<PageResponse<ConfigResponse>> getAllConfigs(ConfigPageRequest configPageRequest) {
        Page<Config> page = new Page<>(configPageRequest.getPage(), configPageRequest.getLimit());
        QueryWrapper<Config> qw = new QueryWrapper<>();
        qw.lambda().orderByAsc(Config::getId);
        IPage<Config> pageData = configMapper.selectPage(page, qw);
        List<Config> records = pageData.getRecords();
        List<ConfigResponse> list = ConfigConvert.INSTANCE.configs2Responses(records);
        return RestResponse.success(new PageResponse<>(list, pageData.getTotal(), configPageRequest.getPage(), configPageRequest.getLimit()));
    }

    @Override
    public RestResponse<ConfigResponse> updateConfig(Config config) {
        config.fillUpdateInfo(httpServletRequest, redisCache);
        configMapper.updateById(config);
        ConfigResponse configResponse = ConfigConvert.INSTANCE.config2Response(config);
        return RestResponse.success(configResponse);
    }
}
